package com.yvtian.admin.service.impl;

import com.google.gson.Gson;
import com.yvtian.admin.service.TokenService;
import com.yvtian.constants.TokenConstants;
import com.yvtian.entity.JWTInfo;
import com.yvtian.utils.JwtTokenUtil;
import com.yvtian.utils.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String refresh(HttpServletRequest request) throws Exception {
//        String oldToken = request.getHeader(TokenConstants.TOKEN_VALUE);
//        if (StringHelper.isEmpty(oldToken)){
//            throw new UserTokenException("token is null");
//        }
//        Claims claims = JwtTokenUtil.getInfoFromToken(oldToken, TokenConstants.SECRET_KEY);
//        JWTInfo jwtInfo = new JWTUtil().getJWTInfo(claims);
//        redisTemplate.expire(RedisConstant.REDIS_USER_TOKEN_KEY + ":" + jwtInfo.getId()
//                ,RedisConstant.REDIS_USER_TOKEN_EXPIRED_TIME, TimeUnit.SECONDS);
//        String userId = request.getHeader("userId");
        String userId = (String) request.getAttribute(TokenConstants.JWT_USER_ID);
        String tokenInfo = redisTemplate.opsForValue().get(RedisConstant.REDIS_USER_TOKEN_KEY + ":" + userId);
        JWTInfo jwtInfo = new Gson().fromJson(tokenInfo, JWTInfo.class);
        return JwtTokenUtil.generateToken(jwtInfo, TokenConstants.SECRET_KEY);
    }

}
